package com.jgp.security.jpa.filters;

import com.jgp.common.persistence.Model;
import com.jgp.security.config.SecUserAdapter;
import com.jgp.sys.props.ClientPropBean;
import com.jgp.sys.query.jpa.ClientFilter;
import com.jgp.sys.utils.SpringContextUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-12-20
 */
public class ClientDataFilter implements ClientFilter {
    
    @Override
    public String getClientId(Class javaType) {
        SecUserAdapter userAdapter = SpringContextUtil.getBean(SecUserAdapter.class);
        String clientId = userAdapter.currentUser().getClientId();
        String[] excludeModels = userAdapter.currentUser().getExcludeModels();
        if(StringUtils.isNotBlank(clientId)&&!ArrayUtils.contains(excludeModels, javaType.getName())){
            return userAdapter.currentUser().getClientId();
        }else{
            return null;
        }
    }
    
    @Override
    public Predicate doPredicate(Root<? extends Model> root, CriteriaBuilder builder) {
        SecUserAdapter userAdapter = SpringContextUtil.getBean(SecUserAdapter.class);
        ClientPropBean clientPropBean = SpringContextUtil.getBean(ClientPropBean.class);
    
        if(Objects.isNull(userAdapter) || Objects.isNull(clientPropBean)){
            return null;
        }
        String clientId = null;
        String[] excludeModels = null;
        if(Objects.nonNull(userAdapter.currentUser())){
            clientId = userAdapter.currentUser().getClientId();
            excludeModels = userAdapter.currentUser().getExcludeModels();
        }else{
            clientId = clientPropBean.getId();
            excludeModels = clientPropBean.getExcludes();
        }
        if(StringUtils.isNotBlank(clientId)&&!ArrayUtils.contains(excludeModels, root.getJavaType().getName())){
            return builder.equal(root.get("clientId"),clientId);
        }
        return null;
    }
}
